<?php
declare(strict_types=1);

namespace app\api\logic;

use app\admin\model\user\UserVipCard;
use app\api\model\UserDoc;
use app\basic\BaseLogic;
use think\facade\Db;

class UserDocLogic extends BaseLogic
{
    protected $userDocModel;

      protected $error;

    public function __construct()
    {
        $this->userDocModel = new UserDoc();
    }

    /**
     * 处理订单支付后的文档购买记录
     * @param int $orderId 订单ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function handleOrderPaid($orderId, $userId)
    {
        try {
            // 获取订单信息
            $orderInfo = Db::name('order')->where('order_id', $orderId)->find();
            if (!$orderInfo || $orderInfo['order_type'] != 1) {
                return true; // 不是文档订单，直接返回成功
            }
            // 获取订单商品信息
            $orderGoods = Db::name('order_goods')
                ->where('order_id', $orderId)
                ->find();
            if (!$orderGoods) {
                $this->setError("订单商品信息不存在");
                return false;
            }
            // 检查是否已购买
            $exists = $this->userDocModel->where([
                'user_id' => $userId,
                'doc_id' => $orderGoods['goods_id'],
                'status' => 1
            ])->find();

            if ($exists) {
                $this->setError("该文档已购买");
                return false;
            }

            // 添加文档购买记录
            $this->userDocModel->save([
                'user_id' => $userId,
                'doc_id' => $orderGoods['goods_id'],
                'create_time' => time(),
                'status' => 1
            ]);

            return true;

        } catch (\Exception $e) {
            $this->setError($e->getMessage());
            return false;
        }
    }

     /**
     * 检查用户是否已购买文档
     * @param int $userId 用户ID
     * @param int $docId 文档ID
     * @return bool
     */
    public function checkUserBought($userId, $docId)
    {
        if (empty($userId)) {
            return false;
        }
        $result = (bool)$this->userDocModel->where([
            'user_id' => $userId,
            'doc_id' => $docId,
            'status' => 1
        ])->find();
        // 判断当前没有购买，判断当前是否是会员
        if(!$result){
            $memberInfo = (new UserVipCard())->where(['user_id' => $userId])->find();
            if (empty($memberInfo)) {
                return false;
            }
            // 判断会员是否有效
            if($memberInfo['end_time'] > time()){
                return true;
            }
        }
        return false;
    }
        public function setError($error)
    {
        $this->error = $error;
    }

    public function getError()
    {
        return $this->error;
    }
}